//
//  SureOderViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/12.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "SureOderViewController.h"
#import "ScorePayViewController.h"
#import "MoneyPayViewController.h"
#import "AddressViewController.h"
#import "MallRequestManager.h"
#import "AddressModel.h"
#import "AllAddressViewController.h"
#import "OrderGoodsInfoModel.h"
#import "OrderDetailViewController.h"
@interface SureOderViewController ()
@property(strong,nonatomic)UIButton *button;
@property(nonatomic,strong)ScorePayViewController *ScorePayVC;
@property(nonatomic,strong)MoneyPayViewController *MoneyPayVC;
@property(nonatomic,strong)UIButton *btnView;
@property(nonatomic,strong)NSDictionary *userInfoDic;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,assign)float minusScore;//需要扣除的积分
@property(nonatomic,assign)float minusMoney;//需扣除的金额
@property (nonatomic,strong)NSMutableDictionary *detailOrderInfo;
@property (nonatomic,strong)NSString *addressid;
//@property (weak, nonatomic) IBOutlet UITableViewCell *billCell;
@property (weak, nonatomic) IBOutlet UITextField *billTextField;
@property (weak, nonatomic) IBOutlet UITextField *companyTextField;
@property (nonatomic,strong)NSString *orderId;
@end

@implementation SureOderViewController
- (IBAction)sureOderBtnClicked:(id)sender
{
    if ([self.addressLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"没有获取到地址信息,请检查网络"];
        return;
    }
        //生成订单
        NSMutableDictionary *params = [NSMutableDictionary new];
        OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        NSString *goodid = [model.standardinfo objectForKey:@"goodid"];
        NSString *standardid = [model.standardinfo objectForKey:@"id"];
        NSString *numString = self.numLabel.text;
        int number = [numString intValue];
        NSNumber *num = [NSNumber numberWithInt:number];
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
        [params setValue:userId forKey:@"user_id"];
        [params setObject:goodid forKey:@"good_id"];
        [params setObject:standardid  forKey:@"standard_id"];
        [params setObject:num forKey:@"good_num"];
        [params setValue:token forKey:@"token"];
    
        NSString *invoicetitle = self.billTextField.text;//可为空
        NSString *invoicenumber = self.companyTextField.text;//可为空
        NSString *message = self.message.text;//可为空
        NSString *order_type = @"2";
    NSString *isexchange = nil;
    if (self.scoreSwitch.on ==YES) {
        isexchange = @"1";
    }else
    {
        isexchange = @"0";//1表示使用积分 2表示不使用积分

    }
    [params setObject:invoicetitle forKey:@"invoicetitle"];
    [params setObject:invoicenumber forKey:@"invoicenumber"];
    [params setObject:self.addressid forKey:@"addressid"];
    [params setObject:isexchange forKey:@"isexchange"];
    [params setObject:message forKey:@"message"];
    [params setObject:order_type forKey:@"order_type"];
    [SVProgressHUD showWithStatus:@"订单提交..."];
    [MallRequestManager post:Queryaddorder RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
            if (connectionError) {
                NSLog(@"connectionError");
                TIPSFORVIEW(@"提交订单失败");
            }
            else{
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
                NSLog(@"订单提交:%@",[dic objectForKey:@"message"]);
                if ([dic.allKeys containsObject:@"result"]) {
                    self.detailOrderInfo = [dic objectForKey:@"result"];
                    [self.detailOrderInfo setObject:@"1" forKey:@"type"];
                    if ([self.detailOrderInfo.allKeys containsObject:@"ispay"]) {
                        if ([[self.detailOrderInfo objectForKey:@"ispay"]isEqualToString:@"0"]) {
                            self.orderId = [self.detailOrderInfo objectForKey:@"orderid"];
                            [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                            [self performSelectorOnMainThread:@selector(PushAfterDelay) withObject:nil waitUntilDone:YES];
                        }else
                        {
//                             [SVProgressHUD showSuccessWithStatus:@"提交订单成功"];
                            
                            [self performSelectorOnMainThread:@selector(DelayshowPayVC) withObject:nil waitUntilDone:YES];
                        }
                    }
                }
            }
        }];
}
- (void)PushAfterDelay
{
    [self performSelector:@selector(PushToOrderVC) withObject:nil afterDelay:1.0f];
}
- (void)PushToOrderVC
{
    OrderDetailViewController *orderDetail = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderDetailViewController"];
    orderDetail.strOrderid = self.orderId;
    orderDetail.flag = @"1";
    [self.navigationController pushViewController:orderDetail animated:YES];
}
- (void)DelayshowPayVC
{

    [self performSelector:@selector(showPayVC) withObject:nil afterDelay:0.0f];
}
- (void)showPayVC
{
    //添加蒙层 弹出付款页面
    self.tableView.scrollEnabled =NO; //设置tableview 不能滚动
    self.btnView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.contentSize.height)];
    self.btnView.backgroundColor = [UIColor grayColor];
    [self.btnView addTarget:self action:@selector(btnViewClicked) forControlEvents:UIControlEventTouchUpInside];
    self.btnView.alpha = 0.6;
    [self.view addSubview:self.btnView];
    _MoneyPayVC = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"MoneyPay"];
    [self addChildViewController:_MoneyPayVC];
    _MoneyPayVC.view.frame = CGRectMake(0, self.tableView.contentSize.height-(self.tableView.contentSize.height-self.tableView.contentOffset.y-self.view.frame.size.height)-300, self.tableView.frame.size.width,300);
    _MoneyPayVC.view.alpha = 1.0;
    [self.view addSubview:_MoneyPayVC.view];
    _MoneyPayVC.flag = @"1";//1表示从实物付款页跳转订单详情
    NSNotification *notification =[NSNotification notificationWithName:SubmitOrdersIsClicked object:nil userInfo:self.detailOrderInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)requestOrderData
{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userId forKey:@"user_id"];
    NSString *goodid = [self.goodInfo objectForKey:@"goodid"];
    NSString *standardid =  [self.goodInfo objectForKey:@"id"];
    [params setObject:goodid forKey:@"good_id"];
    [params setObject:standardid forKey:@"standard_id"];
    NSNumber *goodNum = [NSNumber numberWithInt:[[self.goodInfo objectForKey:@"number"]intValue]];
    [params setObject:goodNum forKey:@"good_num"];
    [params setValue:token forKey:@"token"];
    [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeClear];
    [MallRequestManager post:Orderconfirm RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            NSLog(@"connectionError:%@",connectionError);
        }else
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
            if ([dic.allKeys containsObject:@"result"]) {
                NSDictionary *result = [dic objectForKey:@"result"];
                self.dataSource = [NSMutableArray new];
                [self.dataSource addObject:[OrderGoodsInfoModel appWithDict:result]];
                OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
                if (model.addressinfo.count ==0) {
                    [self performSelectorOnMainThread:@selector(pushToAddressVC) withObject:nil waitUntilDone:YES];
                    return ;
                }
            else
                {
                [self performSelectorOnMainThread:@selector(createUI) withObject:nil waitUntilDone:NO];
                }
            }
        }
    }];
    
}
- (void)pushToAddressVC
{
    AddressViewController *address = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"address"];
    address.flag = 0;
    [self.navigationController pushViewController:address animated:NO];
}
- (void)createUI
{
    [_addBtn setBackgroundImage:[UIImage imageNamed:@"add_disable"] forState:UIControlStateDisabled];
    [_addBtn setBackgroundImage:[UIImage imageNamed:@"add_enable"] forState:UIControlStateNormal];
    [_reduceBtn setBackgroundImage:[UIImage imageNamed:@"minus_enable"] forState:UIControlStateNormal];
    [_reduceBtn setBackgroundImage:[UIImage imageNamed:@"minus_disable"] forState:UIControlStateDisabled];
    
    OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
    NSDictionary *goodInfo1 = model.goodinfo;
    _titleLabel.text = [goodInfo1 objectForKey:@"good_title"];
    _numberLabel.text = [goodInfo1 objectForKey:@"good_num"];
    _numLabel.text = [goodInfo1 objectForKey:@"good_num"];
    _colorLabel.text = [model.standardinfo objectForKey:@"stylename"];
     int stockcount = [[self.goodInfo objectForKey:@"stockcount"]intValue];
    int selectedNum = [[self.goodInfo objectForKey:@"number"]intValue];
    
        if (stockcount>selectedNum) {
            self.addBtn.enabled =YES;
            if (selectedNum ==1) {
                self.reduceBtn.enabled =NO;
            }else
            {
                self.reduceBtn.enabled =YES;
            }
    }else if (stockcount==selectedNum)
    {
        self.addBtn.enabled =NO;
        self.reduceBtn.enabled = YES;
    }
    
    if ([_numLabel.text isEqualToString:@"1"]) {
        _reduceBtn.enabled =NO;
    }
    _priceLabel.text = [NSString stringWithFormat:@"￥%@",[goodInfo1 objectForKey:@"price"]];
    NSDictionary *goodInfo2 = model.standardinfo;
    NSURL *url = [NSURL URLWithString:[goodInfo2 objectForKey:@"styleimage"]];
    [_imgView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"商城首页默认图片"]];
    //详细地址框
    BRPlaceholderTextView *textView = [[BRPlaceholderTextView alloc]init];
    textView.layer.borderColor = RGB(100, 100, 100).CGColor;
    textView.placeholder=@"对本次交易的说明";
    textView.layer.borderWidth = 0;
    [textView addMaxTextLengthWithMaxLength:20 andEvent:^(BRPlaceholderTextView *text) {
        [text endEditing:YES];
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超过指定长度" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
    }];
    _textView = textView;
    if ([[self.goodInfo objectForKey:@"score"]isEqualToString:@"0"]) {
        _scoreLabel.text  = @"无积分可用";
        self.scoreSwitch.on =NO;
        self.scoreSwitch.enabled =NO;
    }else
    {
        [self showBillAndScore];
        self.scoreSwitch.enabled =YES;
    }
    
     self.payMoneyLabel.text = [NSString stringWithFormat:@"￥%.2f", [[self.goodInfo objectForKey:@"number"]intValue]*[[self.goodInfo objectForKey:@"price"]floatValue]];
    //快递及运费
    _expensesLabel.text = [model.expressinfo objectForKey:@"title"];
    _expensesMoneyLabel.text =  [NSString stringWithFormat:@"￥%@",[model.expressinfo objectForKey:@"price"]];
    //地址
    [model.addressinfo objectForKey:@"name"];
    [model.addressinfo objectForKey:@"tel"];
    [model.addressinfo objectForKey:@"province"];
    [model.addressinfo objectForKey:@"city"];
    [model.addressinfo objectForKey:@"address"];
    [model.addressinfo objectForKey:@"district"];
    self.addressid = [model.addressinfo objectForKey:@"id"];
    _nameLabel.text =  [model.addressinfo objectForKey:@"name"];
    _phoneLabel.text = [model.addressinfo objectForKey:@"tel"];
    _addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@",[model.addressinfo objectForKey:@"province"],[model.addressinfo objectForKey:@"city"], [model.addressinfo objectForKey:@"district"],[model.addressinfo objectForKey:@"address"]];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestOrderData];
    self.title =@"确认订单";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newAddress) name:newAddress object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(renewAddress:) name:changeAddressNoti object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeMoneyPayVC) name:removeMoneyPayVCFromType1 object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(popFromAddressVC) name:popFromAddressVC object:nil];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.sureButton.layer.cornerRadius = 25;
    self.billSwitch.on =NO;
    self.scoreSwitch.on = NO;
}
- (void)popFromAddressVC
{
    [self.navigationController popViewControllerAnimated:NO];
}
-(void)dealloc
{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:changeAddressNoti object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:removeMoneyPayVCFromType1 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:newAddress object:nil];
}
- (void)removeMoneyPayVC
{
    self.tableView.scrollEnabled = YES;
    [_MoneyPayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
}
- (void)renewAddress:(NSNotification *)text
{
    NSLog(@"text:%@",text.userInfo);
    AddressModel *model = [text.userInfo objectForKey:@"newAddress"];
    self.nameLabel.text = model.name;
    self.phoneLabel.text = model.tel;
    self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@",model.province,model.city,model.district,model.address];
    self.addressid = model.uid;
    [self.tableView reloadData];
}
- (void)newAddress
{
    {
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:userId forKey:@"user_id"];
        [params setValue:token forKey:@"token"];
        [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeClear];
        [MallRequestManager post:Queryreceivingaddress RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            [SVProgressHUD dismiss];
            if (connectionError) {
                NSLog(@"connectionError:%@",connectionError);
                [self.navigationController popViewControllerAnimated:YES];
            }else
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
                if ([dic.allKeys containsObject:@"result"]) {
                    NSArray *result = [dic objectForKey:@"result"];
                    for (NSDictionary *dic in result) {
                        self.addressInfo = dic;
                    }
                    [self performSelectorOnMainThread:@selector(reloadUI) withObject:nil waitUntilDone:NO];
                }
            }
        }];
    }
}
- (void)reloadUI
{
    if (self.addressInfo.count >0) {
       OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
        model.addressinfo = self.addressInfo;
        [self createUI];
    }else
    {
        [self.navigationController popViewControllerAnimated:YES];
         [[NSNotificationCenter defaultCenter]postNotificationName:noAddressOfScore object:nil];
    }
   
}

- (void)btnViewClicked
{
    self.tableView.scrollEnabled =YES; //设置tableview 能滚动
    [_MoneyPayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
}
#pragma mark - Table view data source
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==1) {
        AllAddressViewController *allAddress = [[AllAddressViewController alloc]init];
        [self.navigationController pushViewController:allAddress animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0) {
        return 150;
    }else if (indexPath.row ==1)
    {
        return 100;
    }else if (indexPath.row ==10)
    {
        return 70;
    }else if (indexPath.row ==6)
    {
        if (self.billSwitch.on ==YES) {
            return 90;
        }else
        {
            if (self.billSwitch.on ==YES) {
                return 50;
            }
            return 0;
        }
    }else
    {
        return 50;
    }
}
//代理要实现的方法
- (void)ChangeAddress:(AddressModel *)model
{
    NSLog(@"addressDic:%@",model);
    self.nameLabel.text  = model.name;
    self.phoneLabel.text =model.tel;
    self.addressLabel.text =[NSString stringWithFormat:@"%@ %@ %@",model.province,model.city,model.address];
}

- (IBAction)billSwitchValueChanged:(UISwitch *)sender {
    
    [self.tableView reloadData];
}
- (IBAction)scoreSwitchValueChanged:(UISwitch *)sender {
    [self showBillAndScore];
}

- (IBAction)reduceBtnClicked:(UIButton *)sender {
    int num = [self.numLabel.text intValue]-1;
    self.numLabel.text = [NSString stringWithFormat:@"%d",num];
    if (num<=1) {
        sender.enabled =NO;
    }else
    {
        self.addBtn.enabled =YES;
    }
    [self showBillAndScore];
}

- (IBAction)addBtnClicked:(UIButton *)sender {
    OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
    int maxNum = [[model.standardinfo objectForKey:@"stockcount"]intValue];
    int num = [self.numLabel.text intValue]+1;
    self.numLabel.text = [NSString stringWithFormat:@"%d",num];
    if ([self.numLabel.text integerValue]>=maxNum) {
        self.reduceBtn.enabled =YES;
        self.addBtn.enabled =NO;
    }else
    {
        self.addBtn.enabled =YES;
        self.reduceBtn.enabled =YES;
        
    }
    [self showBillAndScore];
}
- (void)showBillAndScore
{
    OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
    NSDictionary *goodInfo1 = model.goodinfo;
    //单价
    float price =  [[goodInfo1 objectForKey:@"price"]floatValue];
    //积分
    NSString *minusScore = model.score;
    //积分对应金额
    float scoreNum  = [minusScore floatValue]/100;
    //数量
    int num = [self.numLabel.text intValue];
    //总价
    float sumPrice = price*num;
   
    if (scoreNum<sumPrice) {
        float sumPrice =  price*num-scoreNum;
        
        self.scoreLabel.text = [NSString stringWithFormat:@"可用%.0f积分抵扣%.2f元",scoreNum*100,scoreNum];
        _minusScore = scoreNum*100;
        _minusMoney = sumPrice;
    }else
    {
        scoreNum = price*num;
        self.scoreLabel.text = [NSString stringWithFormat:@"可用%.0f积分抵扣%.2f元",sumPrice*100,sumPrice];
        _minusScore = sumPrice*100;
        _minusMoney = 0.00;
    }

    if (self.scoreSwitch.on ==YES) {
        if (scoreNum<sumPrice) {
            float sumPrice =  price*num-scoreNum;
        self.payMoneyLabel.text = [NSString stringWithFormat:@"￥%.2f",sumPrice];
            _minusScore = scoreNum*100;
            _minusMoney = sumPrice;
        }else
        {
            scoreNum = price*num;
            self.payMoneyLabel.text = [NSString stringWithFormat:@"￥0.00"];
            _minusScore = sumPrice*100;
            _minusMoney = 0.00;
        }
        
    }else
    {
        self.payMoneyLabel.text = [NSString stringWithFormat:@"￥%.2f",sumPrice];
    }
    self.numberLabel.text = self.numLabel.text;
    if ([[self.goodInfo objectForKey:@"score"]isEqualToString:@"0"]) {
        _scoreLabel.text  = @"无积分可用";
        self.scoreSwitch.on =NO;
        self.scoreSwitch.enabled =NO;
    }
    [self.tableView reloadData];
}

@end
